package com.wechat.back.controller;

import com.wechat.back.anno.OptLog;
import com.wechat.back.pojo.tools.PageBean;
import com.wechat.back.pojo.tools.Result;
import com.wechat.back.pojo.User;
import com.wechat.back.service.UserService;
import com.wechat.back.utils.JwtUtil;
import com.wechat.back.utils.Md5Util;
import com.wechat.back.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @OptLog(optModule = "用户模块",optType = "注册", optDesc = "用户注册")
    @RequestMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password, Integer userPower){
        //查询用户
        User u = userService.findByUserName(username);
        System.out.println(u);
        if(u==null){
            //没有占用，注册
            userService.register(username, password, userPower);
            return Result.success();
        }else {
            //占用
            return Result.error("用户名已占用");
        }
    }

//    @OptLog(optModule = "用户模块",optType = "登录", optDesc = "用户登录")
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password){
        //根据用户名查询用户
        User login_user = userService.findByUserName(username);
        if(login_user==null){
            return Result.error("用户名不存在");
        }
        //加密密码与数据库进行比较
        if(Md5Util.getMD5String(password).equals(login_user.getPassword())){
            if(login_user.getUserPower().equals(1)){
                //token失效时间12小时
                Map<String, Object> claims = new HashMap<>();
                claims.put("id",login_user.getId());
                claims.put("username", login_user.getUsername());
                String token = JwtUtil.genToken(claims);
                //redis
                ValueOperations<String,String> operations = stringRedisTemplate.opsForValue();
                operations.set(token,token,12, TimeUnit.HOURS);//失效12小时
                return Result.success(token);
            }else {
                return Result.error("账号异常，请联系客服");
            }
        }
        return Result.error("密码错误");
    }


    //查询用户信息
    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token*/){
//        Map<String, Object> claims = JwtUtil.parseToken(token);
//        String username = (String) claims.get("username");
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }

    @GetMapping("/userInfoById")
    public Result<User> userInfoById(Integer id){
        User user = userService.findById(id);
        return Result.success(user);
    }

    //更改用户信息
    @OptLog(optModule = "用户模块",optType = "修改", optDesc = "修改用户信息")
    @PutMapping("/update")
    //@Validated使校验生效
    public Result update(@RequestBody @Validated User user){
        System.out.println(user);
        userService.update(user);
        return Result.success("更改成功");
    }

    //更新用户状态
//    @OptLog(optModule = "用户模块",optType = "修改", optDesc = "修改用户状态")
    @PatchMapping("/updateStatus")
    public Result updateStatus(String userStatus){
        userService.updateStatus(userStatus);
        return Result.success("更改成功");
    }

    //更新用户权限
    @OptLog(optModule = "用户模块",optType = "修改", optDesc = "修改用户权限")
    @PatchMapping("/updatePower")
    public Result updatePower(Integer id,Integer userPower){
        userService.updatePower(id,userPower);
        return Result.success("更改成功");
    }

    //设置头像
    @OptLog(optModule = "用户模块",optType = "修改", optDesc = "修改用户头像")
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success("更新成功");
    }

    @OptLog(optModule = "用户模块",optType = "修改", optDesc = "修改用户密码")
    @PatchMapping("updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params/*String username*/){
        //校验参数
//        String oldPwd = params.get("old_pwd");
        String username = params.get("username");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        //校验非空
        User loginUser = userService.findByUserName(username);
        Integer id = loginUser.getId();
        //校验新密码与确认密码是否相同
        if(!rePwd.equals(newPwd)){
            return Result.error("两次填写的密码不一样");
        }else {
            //密码更新
            userService.updatePwd(id,newPwd);
            return Result.success("修改成功");
        }
    }

    @GetMapping("/list")
    public Result<PageBean<User>> list(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) String username
    ) {
        PageBean<User> pb =  userService.list(pageNum,pageSize,username);
        return Result.success(pb);
    }
}
